package com.lestv.activitys;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.lestv.application.LestvApplication;
import com.lestv.entity.User;
import com.lestv.httpUtil.Cache;
import com.lestv.httpUtil.HttpRequestParams;
import com.lestv.httpUtil.HttpUtils;
import com.lestv.httpUtil.NetHandler;
import com.lestv.httpUtil.OnComplteListener;
import com.lestv.jsonBeans.BaseBean;
import com.lestv.jsonParser.BaseParser;
import com.lestv.util.SharedPrefHelper;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 登录界面
 * @author Administrator
 * adb connect 127.0.0.1:26944
 */
@SuppressLint("ShowToast")
public class LoginActivity extends FragmentActivity implements OnClickListener{
	//用户名输入框
	private EditText userName;
	//密码输入框
	private EditText userPass;
	//登录按钮
	private Button login;
	//注册链接
	private TextView register;
	//登录之后在手机上保存帐号和密码
	private SharedPrefHelper instance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		this.userName = (EditText) findViewById(R.id.phonenum);
		this.userPass = (EditText) findViewById(R.id.password);
		this.login = (Button) findViewById(R.id.login);
		this.register = (TextView) findViewById(R.id.login_register);
		this.login.setOnClickListener(this);
		this.register.setOnClickListener(this);
		this.instance = SharedPrefHelper.getInstance(getApplicationContext());
		//获取本手机上是否登录过此APP
		String userName = instance.getUserName();
		//电话号码进行判断，之前是否登陆过，如果登陆过那么直接获取数据，如果没有登陆过那么从输入框里面进行获取数据
		//判断如果电话号码不为空
		if (StringUtils.isNotEmpty(userName)) {
			String userPass = instance.getUserPass();
			this.userName.setText(userName);
			this.userPass.setText(userPass);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.login:
				this.login();
				break;
			case R.id.login_register:
				//跳转到注册界面
				Intent it = new Intent(LoginActivity.this, RegisterActivity.class);		
				startActivity(it);
				overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
				break;
			default:
				break;
		}
	}
	
	/**
	 * 登录
	 */
	public void login() {
		String userName = this.userName.getText().toString();
		String userPass = this.userPass.getText().toString();
		if(StringUtils.isNotEmpty(userName.trim())) {
			if(StringUtils.isNotEmpty(userPass.trim())) {
				this.conectNet(userName.trim(), userPass.trim());
			}else {
				Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
			}
		}else{
			Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * 发送登录请求
	 * @param userName
	 * @param userPass
	 */
	private void conectNet(final String userName, final String userPass){
		HttpUtils hu = new HttpUtils();
		Map<String, String> map = new HashMap<String, String>();
		map.put("userName", userName);
		map.put("userPass", userPass);
		String entity = hu.getEntity(map);
		String path = Cache.LOGIN + "?" + entity;
		HttpRequestParams params = new HttpRequestParams(path, "utf-8",null);
		params.setMethod("GET");
		//模拟ajax异步跨域访问web服务器获取返回json信息
		hu.startConnectNet(params, new BaseParser(), new NetHandler(new OnComplteListener() {
			@Override
			public void success(BaseBean baseBean) {
				// 成功
				if ((baseBean.getEcode() == 200)) {
					Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
					instance.setUserName(userName);
					instance.setUserPass(userPass);
					String userJson = baseBean.getData().get("currentUser").toString();
					User currentUser = JSON.parseObject(userJson, User.class);
					Log.e("成功登录用户", currentUser.toString());
					//登陆成功进入主界面  将当前登录用户对象保存到application范围 整个APP范围有效
					((LestvApplication)getApplication()).setUser(currentUser);
					Intent it = new Intent(LoginActivity.this, MainActivity.class);
					//Activity之间利用Intent传递数据，类似java的请求派发，将数据保存在Intent范围之内，只在下一个Activity有效
					//Intent传递数据支持java的8种基本数据类型、数组、集合、自定义实体类型（必须实现Serializable接口,有setter/getter方法、有无参构造方法）
					//it.putExtra("currentUser", currentUser);
					startActivity(it);
					//实现淡入淡出的效果 第一个参数为启动时动画效果，第二个参数为退出时动画效果 
					overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);    
					//由左向右滑入的效果 第一个参数为启动时动画效果，第二个参数为退出时动画效果 
					//overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
				}else {
					//失败
					Toast.makeText(LoginActivity.this, baseBean.getErrorinfo(), Toast.LENGTH_SHORT).show();
				}
			}
			@Override// 失败
			public void fail() {
				System.out.println("失败");
			}
			@Override// 报错
			public void error(Exception e) {
				System.out.println("报错");
			}
		}));
	}
}
